package logic

import (
	"context"
	"fmt"
	"strings"

	"go-zero-mall/app/admin/cmd/rpc/internal/svc"
	"go-zero-mall/app/admin/cmd/rpc/pd"
	"go-zero-mall/app/admin/model"

	"github.com/zeromicro/go-zero/core/logx"
)

type AdminRoleUpdateLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewAdminRoleUpdateLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AdminRoleUpdateLogic {
	return &AdminRoleUpdateLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 管理员-更新角色
func (l *AdminRoleUpdateLogic) AdminRoleUpdate(in *pd.UmsAdminRoleUpdateReq) (*pd.Response, error) {
	d := model.UmsAdminRoleRelation{
		Id:      in.Id,
		RoleIds: strings.Replace(strings.Trim(fmt.Sprint(in.RoleIds), "[]"), " ", ",", -1),
	}
	//检查id 是否存在,不存在新增
	one, err := l.svcCtx.UmsAdminRoleRelationModel.FindOne(l.ctx, in.Id)
	if err != nil && err != model.ErrNotFound {
		return nil, err
	}
	if one == nil {
		err = l.svcCtx.UmsAdminRoleRelationModel.InsertById(l.ctx, &d)
		if err != nil {
			return nil, err
		}
		return &pd.Response{}, nil
	}
	err = l.svcCtx.UmsAdminRoleRelationModel.Update(l.ctx, &d)
	if err != nil {
		return nil, err
	}
	return &pd.Response{}, nil
}
